<?php

declare(strict_types=1);


namespace App\Middleware;

use App\Constants\CodeData;
use App\Exception\MessageException;
use App\Services\RsaService;
use App\Utils\LoggerUtil;
use Hyperf\Context\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RsaMiddleware implements MiddlewareInterface
{
    private RsaService $rsaService;

    public function __construct(RsaService $service)
    {
        $this->rsaService = $service;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $requestParams = $request->getParsedBody();
        if (!empty($requestParams['encode_data'])) {
            try {
                $decodeParams = $this->rsaService->serverDecode($requestParams['encode_data']);
                $request = $request->withQueryParams(array_merge($requestParams, $decodeParams));
                $request = $request->withParsedBody(array_merge($requestParams, $decodeParams));
                Context::set(ServerRequestInterface::class, $request);
            } catch (\Throwable $e) {
                LoggerUtil::write('RsaMiddleware', $e->getMessage());
                throw new MessageException('数据解密失败！', CodeData::RSA_DECODE_ERROR, ['result' => 4, 'msg' => $e->getMessage()]);
            }
        }
        return $handler->handle($request);
    }


}